package com.coupon.gateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 王哲
 * @Contact 1121586359@qq.com
 * @ClassName RateLimiterFilter.java
 * @create 2023年06月23日 下午9:52
 * @Description 限流过滤器
 * @Version V1.0
 */
@Component
@Slf4j
@SuppressWarnings("all")
public class RateLimiterFilter extends AbstractPreZuulFilter {

    // 每秒可以获取到2个令牌
    RateLimiter rateLimiter = RateLimiter.create(2.0);

    @Override
    protected Object cRun() {

        HttpServletRequest request = requestContext.getRequest();

        if (rateLimiter.tryAcquire()) {
            log.info("成功获取令牌");
            return success();
        } else {
            log.error("error ：rate limit 请求被拦截的地址：{}", request.getRequestURL());
            return fail(402,"error ：rate limit");
        }

    }

    @Override
    public int filterOrder() {
        return 2;
    }
}
